package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.FalseCluePoolDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@SuppressWarnings("all")
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessMapper businessMapper;


    @Override
    public PageResult<FalseCluePoolDO> falseCluePool(FalseCluePoolDTO dto) {
        Page pages = new Page<>(dto.getPage(),dto.getPageSize());
        dto.setStatus(ClueStatusConstants.FAKE_CLUE);
        Page<FalseCluePoolDO> page = this.baseMapper.getFalseCluePool(pages,dto);
        return PageResult.<FalseCluePoolDO>builder()
                .total(page.getTotal())
                .rows(page.getRecords())
                .build();
    }


    @Override
    public void toFalseClue(Integer id, FalseClueDTO falseClueDTO) {
        if (BeanUtil.hasNullField(falseClueDTO, "remark")) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = this.clueMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        clueTrackRecordMapper.insert(ClueTrackRecord.builder()
                .clueId(id)
                .userId(CurrentUserContextHolders.get())
                .type(ClueTrackRecordType.FAKE)
                .falseReason(falseClueDTO.getReason())
                .record(falseClueDTO.getRemark())
                .createTime(LocalDateTime.now())
                .build());
    }
    //转为商机
    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.getById(id);
        //更新线索，重点在于状态
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        //组装商机对象
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        this.businessMapper.insert(business);
    }

    //线索跟进
//    @Transactional(rollbackFor = Exception.class)//指定异常时回滚事务
    //运行时异常回滚事务
    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO updateClueInfoDTO) {
        //更新线索信息
        Clue clue = BeanUtil.copyProperties(updateClueInfoDTO,Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if(clue.getStatus()==ClueStatusConstants.WAIT_FOLLOW_UP) clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        this.updateById(clue);
        //异常时回滚之前执行的sql语句
        // 1/0;
        //新增跟进记录
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(updateClueInfoDTO,ClueTrackRecord.class);
        clueTrackRecord.setId(null);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecordMapper.insert(clueTrackRecord);
    }



    @Override
    public ClueVO getClueById(Integer id) {
        //根据id获取线索
        Clue clue = this.getById(id);
        //根据用户id获取负责跟进的用户信息
        User user = userMapper.getById(clue.getUserId());
        //将线索信息转移到 vo中
        ClueVO clueVO = BeanUtil.copyProperties(clue,ClueVO.class);
        //根据线索id获取跟进记录
        List<ClueTrackRecord> trackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId,id)
        );
        //将跟进记录转移到vo中
        List<ClueVO.ClueTrackRecordVO> list = trackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item,ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        //将跟进记录VO放进ClueVO中
        clueVO.setTrackRecords(list);
        //返回ClueVO
        return clueVO;
    }


    //新增线索
    @Override
    public void addClue(ClueDTO clueDTO) {
        if (ObjectUtil.isEmpty(clueDTO.getChannel())|| ObjectUtil.isEmpty(clueDTO.getPhone())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(clueDTO,Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }

    @Override
    public PageResult<ClueDO> listClues(ClueListDTO dto) {

/*        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        List<ClueDO> list = clueMapper.selectByPage(dto);
        Page<ClueDO> page = (Page<ClueDO>) list;
        return PageResult.<ClueDO>builder()
                .total(page.getTotal())
                .rows(page)
                .build();*/
        return this.clueListMp(dto);
    }
    /**
     * 线索列表查询 使用MP的方式处理
     * @param dto 查询参数
     * @return 线索列表
     *   MP中如果是多表查询此时无法使用自带分页方法page，可以将分页参数封装到Mapper方法中第一个参数(com.baomidou.mybatisplus.extension.plugins.pagination.Page)中即可！
     *   Mapper 方法返回值直接使用 baomidou的 Page
     */
    private PageResult<ClueDO> clueListMp(ClueListDTO dto){
        Page pages = new Page<>(dto.getPage(), dto.getPageSize());
        Page<ClueDO> clueDOPage = this.baseMapper.selectByPageMp(pages, dto);
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(clueDOPage.getTotal()).intValue())
                .rows(clueDOPage.getRecords())
                .build();
    }
}